package com.zkingsoft.common.tools;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.matrix.core.exception.GlobleException;
import com.matrix.core.tools.EncrypUtil;
import com.matrix.core.tools.FileType;
import com.matrix.core.tools.FileTypeUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.zkingsoft.common.constance.AppConstance;

/**
 * 文件上传
 * 
 * @author JIANGYOUYAO
 * @email 935090232@qq.com
 * @date 2018年6月15日
 */
public class UploadUtil {

	private static String STATUSS = "status";
	private static String MSG = "msg";

	/**
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年6月15日
	 * @param response
	 * @param request
	 * @param extList
	 * @param folderType
	 * @param userId
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 */

	public static Map<String, String> doUpload(MultipartHttpServletRequest request, List<FileType> extList,
			String folderType, String userId) throws NoSuchAlgorithmException, IOException {
		Map<String, String> resourceMap = new HashMap<>();

		// 图片保存目录路径
		String baseSavePath = PropertiesUtil.getString(AppConstance.FILES_TORAGE_PATH);
		// 图片保存目录URL
		String baseSaveUrl = PropertiesUtil.getString(AppConstance.NGINX_URL);
		// 检查目录
		File uploadDir = new File(baseSavePath);
		if (!uploadDir.isDirectory()) {
			uploadDir.mkdir();
		}

		// 保存和访问路径检查
		if (StringUtils.isBlank(baseSaveUrl) || StringUtils.isBlank(baseSavePath)) {
			resourceMap.put(STATUSS, "err");
			resourceMap.put(MSG, "服务器图片保存路径配置错误");
			return resourceMap;
		}

		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			resourceMap.put(STATUSS, "err");
			resourceMap.put(MSG, "上传目录没有写权限");
			return resourceMap;
		}

		Map<String, MultipartFile> fileMaps = request.getFileMap();
		for (String key : fileMaps.keySet()) {
			MultipartFile file = fileMaps.get(key);
			if (!FileTypeUtil.checkFileType(file.getInputStream(), extList)) {
				resourceMap.put(STATUSS, "err");
				resourceMap.put(MSG, "文件类型不正确");
				return resourceMap;
			}
			// 拼接64位文件名
			String fileName = file.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			String newFileName = UUIDUtil.getRandomID() + UUIDUtil.getRandomID() + "." + fileExt;
			Map<String, String> fileUrlMap = fileUrl(baseSavePath, baseSaveUrl, folderType, userId);
			String savePath = fileUrlMap.get("savePath");
			String saveUrl = fileUrlMap.get("saveUrl");
			File uploadedFile = new File(savePath, newFileName);
			try {
				FileCopyUtils.copy(file.getBytes(), uploadedFile);
			} catch (IOException e) {
				resourceMap.put(STATUSS, "err");
				resourceMap.put(MSG, "文件上传失败" + e.getMessage());
				return resourceMap;
			}
			// 图片访问地址
			String visitPath = saveUrl + newFileName;
			String fileSize = file.getBytes().length + "";
			// 保存图片大小
			resourceMap.put("fileSize", fileSize);
			// 图片访问地址
			resourceMap.put("visitPath", visitPath);
			resourceMap.put("savePath", savePath + newFileName);

		}
		resourceMap.put(STATUSS, "ok");
		resourceMap.put(MSG, "图片上传成功");
		return resourceMap;
	}

	/**
	 * 加載保存文件路徑
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年6月15日
	 * @param savePath
	 * @param saveUrl
	 * @param folderType
	 * @param userId
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	public static Map<String, String> fileUrl(String savePath, String saveUrl, String folderType, String userId)
			throws UnsupportedEncodingException, NoSuchAlgorithmException {
		Map<String, String> fileUrlMap = new HashMap<>();

		// 创建图片文件夹
		savePath += folderType + "/";
		saveUrl += folderType + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}

		// 以账号ID命名创建文件夹
		/*String encryptionId = EncrypUtil.getSha1(userId);
		savePath += encryptionId + "/";
		saveUrl += encryptionId + "/";
		File userIdFile = new File(savePath);
		if (!userIdFile.exists()) {
			userIdFile.mkdirs();
		}*/

		// 创建日期文件夹
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		fileUrlMap.put("savePath", savePath);
		fileUrlMap.put("saveUrl", saveUrl);
		return fileUrlMap;

	}

}
